/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Views;

import Classes.Imprimante;
import Classes.Materiel;
import Classes.Ordinateur;
import Classes.Retroprojecteur;
import DAO.*;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Valentin
 */
public class vueRechercheCodeBarre extends javax.swing.JFrame {

    private vueGlobale mainFrame;
    private String numCB;
    private int idType;
    private Ordinateur myOrdinateur;
    private Imprimante myImprimante;
    private Retroprojecteur myRetroprojecteur;
    private Materiel myMateriel;
    private MaterielDAO myMaterielDAO;
    private RetroprojecteurDAO myRetroprojecteurDAO;
    private ImprimanteDAO myImprimanteDAO;
    private DefaultTableModel TableCommonModel;
    private DefaultTableModel TableSpecifModel;

    /**
     * Creates new form vueRechercheCodeBarre
     */
    public vueRechercheCodeBarre() {
        initComponents();

        TableCommonModel = (DefaultTableModel) TableCommon.getModel();
        TableSpecifModel = (DefaultTableModel) TableSpecif.getModel();
    }

    public vueRechercheCodeBarre(JFrame mainFrame) {
        initComponents();

        TableCommonModel = (DefaultTableModel) TableCommon.getModel();
        TableSpecifModel = (DefaultTableModel) TableSpecif.getModel();
        this.mainFrame = (vueGlobale) mainFrame;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        EDT_CB = new javax.swing.JTextField();
        BTN_Valider = new javax.swing.JButton();
        BTN_Retour = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TableCommon = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        TableSpecif = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        EDT_CB.setText("n° de code barre");
        EDT_CB.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                EDT_CBFocusGained(evt);
            }
        });

        BTN_Valider.setText("Valider");
        BTN_Valider.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BTN_ValiderActionPerformed(evt);
            }
        });

        BTN_Retour.setText("Retour");
        BTN_Retour.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BTN_RetourActionPerformed(evt);
            }
        });

        TableCommon.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "<html><b>Nom</b>", "<html><b>N° serie", "<html><b>N° compta", "<html><b>Descriptif", "<html><b>Date achat", "<html><b>Prix HT", "<html><b>Garantie", "<html><b>Num Bc", "<html><b>Budget", "<html><b>Amortissement"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        TableCommon.setRowHeight(20);
        jScrollPane1.setViewportView(TableCommon);

        TableSpecif.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null},
                {null}
            },
            new String [] {
                ""
            }
        ));
        TableSpecif.setRowHeight(20);
        jScrollPane2.setViewportView(TableSpecif);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(BTN_Retour))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(EDT_CB, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(BTN_Valider)
                        .addGap(0, 688, Short.MAX_VALUE)))
                .addContainerGap())
            .addComponent(jScrollPane2)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(EDT_CB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BTN_Valider))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BTN_Retour)
                .addGap(23, 23, 23))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        this.mainFrame.setVisible(true);
    }//GEN-LAST:event_formWindowClosed

    private void BTN_RetourActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BTN_RetourActionPerformed
        this.dispose();
    }//GEN-LAST:event_BTN_RetourActionPerformed

    private void BTN_ValiderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BTN_ValiderActionPerformed
        numCB = EDT_CB.getText();
        if (numCB.matches("^[0-9]{13}$")) {
            decode_CB();
            loadMateriel();
            LoadTables();

        } else {
            JOptionPane.showMessageDialog(this, "Code barre erroné");
        }
    }//GEN-LAST:event_BTN_ValiderActionPerformed

    private void EDT_CBFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_EDT_CBFocusGained
        EDT_CB.selectAll();
    }//GEN-LAST:event_EDT_CBFocusGained

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(vueRechercheCodeBarre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(vueRechercheCodeBarre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(vueRechercheCodeBarre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(vueRechercheCodeBarre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new vueRechercheCodeBarre().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BTN_Retour;
    private javax.swing.JButton BTN_Valider;
    private javax.swing.JTextField EDT_CB;
    private javax.swing.JTable TableCommon;
    private javax.swing.JTable TableSpecif;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
/**
 * Permet de récupérer l'id de type materiel permettant de charger 
 * les informations correspondantes
 */
    private void decode_CB() {
        idType = Integer.decode(numCB.substring(4, 7));
    }
/**
 * Charge le matériel correspondant au type de matériel renseigné dans le code barre
 */
    private void loadMateriel() {
        switch (idType) {
//materiel
            case 1:
                myMaterielDAO = new MaterielDAO(DBConnect.getInstance());
                myMateriel = new Materiel();
                myMateriel = myMaterielDAO.loadByCodeBarre(Long.decode(numCB));

                break;
//imprimante
            case 3:
                myImprimanteDAO = new ImprimanteDAO(DBConnect.getInstance());
                myImprimante = new Imprimante();
                myImprimante = myImprimanteDAO.loadByCodeBarre(Long.decode(numCB));

                break;
//retroprojecteur
            case 4:
                myRetroprojecteurDAO = new RetroprojecteurDAO(DBConnect.getInstance());
                myRetroprojecteur = new Retroprojecteur();
                myRetroprojecteur = myRetroprojecteurDAO.loadByCodeBarre(Long.decode(numCB));

                break;

//ordinateur
//            case 2:
//
//                break;

//oscilloscope
//            case 5:
//
//                break;
////mobilier
//            case 6:
//
//                break;
//default                
            default:
                myMaterielDAO = new MaterielDAO(DBConnect.getInstance());
                myMateriel = new Materiel();
                myMateriel = myMaterielDAO.loadByCodeBarre(Long.decode(numCB));

        }
    }
/**
 * affiche les informations dans les tableaux
 */
    private void LoadTables() {
        while (TableCommonModel.getRowCount() != 0) {
            TableCommonModel.removeRow(0);
        }
        while (TableSpecifModel.getRowCount() != 0) {
            TableSpecifModel.removeRow(0);
        }
        String[] i = {""};
        TableSpecifModel.setColumnIdentifiers(i);
        switch (idType) {
//materiel
            case 1:
                if (myMateriel.getNumCB() == 0) {
                    JOptionPane.showMessageDialog(this, "Code barre introuvable en base de données");
                } else {
                    loadCommonTable(myMateriel);
                }


                break;
//imprimante
            case 3:
                if (myImprimante.getNumCB() == 0) {
                    JOptionPane.showMessageDialog(this, "Code barre introuvable en base de données");
                } else {
                    loadCommonTable(myImprimante);
                    String[] colIdentifiers = {"<html><b>RefCC", "<html><b>RefCN", "<html><b>USB", "<html><b>Parallele", "<html><b>Réseau", "<html><b>Type", "<html><b>A3", "<html><b>A4"};
                    TableSpecifModel.setColumnIdentifiers(colIdentifiers);
                    Vector myVector = new Vector();

                    myVector.add(myImprimante.getRefCC());
                    myVector.add(myImprimante.getRefCN());
                    myVector.add(ifThen(myImprimante.getPortUsb()));
                    myVector.add(ifThen(myImprimante.getPortParallele()));
                    myVector.add(ifThen(myImprimante.getPortRes()));
                    myVector.add(myImprimante.getTypeImpression());
                    myVector.add(ifThen(myImprimante.getFormatA3()));
                    myVector.add(ifThen(myImprimante.getFormatA4()));

                    TableSpecifModel.addRow(myVector);
                }

                break;
//retroprojecteur
            case 4:
                if (myRetroprojecteur.getNumCB() == 0) {
                    JOptionPane.showMessageDialog(this, "Code barre introuvable en base de données");
                } else {
                    loadCommonTable(myRetroprojecteur);
                    String[] colIdentifiers = {"<html><b>Type d'ampoule"};
                    TableSpecifModel.setColumnIdentifiers(colIdentifiers);
                    Vector myVector = new Vector();
                    myVector.add(myRetroprojecteur.getTypeAmp());
                    TableSpecifModel.addRow(myVector);
                }


                break;

//ordinateur
//            case 2:
//
//                break;

//oscilloscope
//            case 5:
//
//                break;
////mobilier
//            case 6:
//
//                break;
//default                
            default:
                if (myMateriel.getNumCB() == 0) {
                    JOptionPane.showMessageDialog(this, "Code barre introuvable en base de données");
                } else {
                    loadCommonTable(myMateriel);
                }


        }

    }
/**
 * affiche les valeurs commune a tout type de matériel
 * @param myMateriel 
 */
    private void loadCommonTable(Materiel myMateriel) {
        Vector myVector = new Vector();
        myVector.add(myMateriel.getNom());
        myVector.add(myMateriel.getNumSerie());
        myVector.add(myMateriel.getNumCompta());
        myVector.add(myMateriel.getDescriptif());
        myVector.add(myMateriel.getDateHT());
        myVector.add(myMateriel.getPrixHT());
        myVector.add(myMateriel.getGarantie());
        myVector.add(myMateriel.getNumBC());
        myVector.add(myMateriel.getBudget());
        myVector.add(myMateriel.getAmortissement());
        TableCommonModel.addRow(myVector);

    }
/**
 * Retourne "oui" si true
 * "non" si false
 * utiliser pour afficher les boolean dans les tableaux
 * @param b
 * @return 
 */
    private String ifThen(String b) {
        String res = "non";
        if (b.equals("1")) {
            res = "oui";
        }
        return res;

    }
}
